<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix"><span>资源树</span></div>
      <el-tree class="filter-tree" show-checkbox :data="datas" :props="defaultProps" 
      node-key="id" @check="getCheckedKeys"  
      default-expand-all :filter-node-method="filterNode" ref="tree"
      ></el-tree>
    </el-card>
  </div>
</template>

<script>
import { getTree } from "@/api/resources";

export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted: function() {
    this.queryData();
  },
  props: ["resourcesIds"],
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    queryData() {
      getTree().then(response => {
        this.datas = response.data;
      });
    },
    getCheckedKeys(a, b) {
      this.resourcesIds.length = 0
      b.checkedKeys.forEach(element => {
        this.resourcesIds.push(element)
      });
    },
    setCheckedKeys(keys) {
      this.$refs.tree.setCheckedKeys(keys);
    }
  },
  data() {
    return {
      filterText: "",
      datas: [],
      defaultProps: {
        children: "children",
        label: "label",
        id: "id"
      }
    };
  }
};
</script>

